/**
 * Created by user on 2017/12/17.
 */
import Sequelize from "sequelize";

let databasename = "persistent";//数据库名
let username = "root";//用户名
let password = "5tgb^YHN";//密码
let host="db.zankong.com.cn";

const sequelize = new Sequelize(
    databasename, username, password,
    {
        host, //连接数据库的主机
        logging: null,//用于Sequelize日志打印的函数,参数为方法
        dialect: "mysql",//要连接的数据库类型。可选值有：mysql、postgres、sqlite、mariadb、mssql
        timezone: '+08:00', //东八时区
    });

const dbFunctions = sequelize.define('functions',
    {
        id: {type: Sequelize.BIGINT, primaryKey: true},
        name: {type: Sequelize.STRING, allowNull: false},
        instanceID: {type: Sequelize.STRING, allowNull: false},
    },
    {
        createdAt: false,
        updatedAt: false,
    });

const dbCodes = sequelize.define("codes",
    {
        name: {type: Sequelize.STRING, allowNull: false, primaryKey: true},
        code: {type: Sequelize.TEXT, allowNull: false},
    },
    {
        createdAt: false,
        updatedAt: false,
    });

const dbInstances = sequelize.define('instances',
    {
        id: {type: Sequelize.BIGINT, primaryKey: true},
        father: {type: Sequelize.STRING, allowNull: true},
        instanceJSON: {type: Sequelize.TEXT, allowNull: false}, //json with functionObj
    },
    {
        createdAt: false,
        updatedAt: false,
    });

const dbObjects = sequelize.define('objects',
    {
        id: {type: Sequelize.BIGINT, primaryKey: true},
        json: {type: Sequelize.TEXT, allowNull: false}, //json with functionObj
    },
    {
        createdAt: false,
        updatedAt: false,
    });


const dbEvents = sequelize.define('Events',
    {
        name: {type: Sequelize.STRING, primaryKey: true},
        funID: {type: Sequelize.STRING, allowNull: false},
        opts: {type: Sequelize.STRING, allowNull: false},
        type: {type: Sequelize.STRING, allowNull: false},
    },
    {
        indexes: [{fields: ["type"]}],//	Array.<String | Object>	建立索引的字段数组。每个字段可以是一个字段名，sequelize 对象 (如 sequelize.fn)，
        //或一个包含：attribute (字段名)、length (创建前缀字符数)、order (列排序方向)、collate (较验的字段集合 (排序))
        createdAt: false, //如果为字符串，则使用提供的值代替 createdAt 列的默认名，设置为flase则不添加这个字段
        updatedAt: false//如果为字符串，则使用提供的值代替 updatedAt 列的默认名，设置为flase则不添加这个字段
    });

const log = sequelize.define('log',
    {
        message: {type: Sequelize.STRING, allowNull: false},
        etc: {type: Sequelize.TEXT, allowNull: false},
    });

export default async ()=> {
    await sequelize.sync();
    await log.create({message:"restarted...", etc:""});
    return {
        Instances: {
            async put(pck) {
                let {id, father, instanceJSON} = pck;
                await dbInstances.upsert(pck)
            },
            async get(id) {
                //console.log(`get instance:${id}`);
                return await dbInstances.findOne({where:{id}});
            },
        },
        Functions: {
            async put(args) {
                let {id} = args;
                await dbFunctions.upsert(args);
            },
            async get(id) {
                let fun=await dbFunctions.findOne({where:{id}});
                return fun;
            },
        },
        Objects: {
            async put(args) {
                let {id, json} = args;
                await dbObjects.upsert(args);
            },
            async get(id) {
                return (await dbObjects.findOne({where:{id}})).json;
            }
        },
        Codes: {
            async put(args) {
                let {name, code} = args;
                await dbCodes.upsert(args);
            },
            async get(name) {
                let codePck=(await dbCodes.findOne({where:{name}}));
                return codePck.code;
            }
        },
        Events: {
            async put(eventObj) {
                eventObj.opts=JSON.stringify(eventObj.opts);
                await dbEvents.upsert(eventObj);
            },
            async get(name) {
                console.log(`get event ${name}`);
                let obj= await dbEvents.findOne({where:{name}});
                obj.opts=JSON.parse(obj.opts);
                return obj;
            },
            async getAll(where){
                let ls=await dbEvents.findAll({where:where});
                for (let e of ls)
                    e.opts=JSON.parse(e.opts);
                return ls;
            },
            async unlisten(name){
                return await dbEvents.destroy({where:{name:name}});
            },
        },
        dump() {
        }
    }
};


